<template>
    <view class="goods-detail-page">
        <view class="banner-box">
            <swiper 
                class="banner"  
                autoplay
                @change="swiperIndex = $event.detail.current"
            >
                <swiper-item class="item" v-for="(item, i) in detail?.goodsGallery" :key="i">
                    <view class="item__inner">
                        <image :src='item.url'/>
                    </view>
                </swiper-item>
            </swiper>   
            <view class="indicator">{{ swiperIndex + 1 }} / {{ detail?.goodsGallery?.length }}</view>
        </view>
        <view class="base-info">
            <view class="price-wrapper">
                <text class="unit">￥</text>
                <text class="value">{{roundToDecimal(detail.price,2)}}</text>
            </view>
            <text class="name">{{detail.goodsName}}</text>
            <view class="bage-warp">
				<view class="bage new" v-if="detail.isHot">热门</view>
				<view class="bage hot" v-if="detail.isNew">新品</view>
			</view>
        </view>
        <view class="cell" v-if="detail.spec.length>1" @click="popupShow=true">
            <view class="cell-main">
                <view class="cell-title">选择:</view>
                <view class="cell-content">{{attrString}}</view>
            </view>
			<icon-xiangyou color="#999" size="28"></icon-xiangyou>
        </view>
        <template v-if="detail.goodsDesc">
            <view class="block">
                <text class="block__label">商品描述</text>
            </view>
            <view class="goods-detail">
                <u-read-more color="#ff0000" showHeight="150">
                    <rich-text :nodes="detail.goodsDesc"></rich-text>
                </u-read-more>
            </view>
        </template>
        <view class="block">
            <text class="block__label">商品详情</text>
        </view>
        <view class="goods-detail">
            <u-parse :content="detail.goodsContent" v-if="detail.goodsContent"></u-parse>
            <u-empty mode="data" v-else></u-empty>
        </view>
        <view class="tabbar">
            <view class="btn" @click="swi('/pages/index/index')">
                <u-icon name="home" size="20"></u-icon>
                <view class="b-text">首页</view>
            </view>
            <view type="default" class="btn">
                <button type="default" open-type="share" class="btn">
                    <u-icon name="share" size="20"></u-icon>
                    <view class="b-text">分享</view>
               </button>
            </view>
            <view class="btn" @click="swi('/pages/car/index')">
                <up-badge max="99" :value="cartTotal.totalQuantity" absolute :offset="[-5,0]"></up-badge>
                <uni-icons type="cart" size="20"></uni-icons>
                <view class="b-text">购物车</view>
            </view>
            <view class="btn">
                <uni-icons type="star-filled" size="20" color="#ffc107" v-if="detail.collectId" @click="goodsCollectCancel()"></uni-icons>
                <uni-icons type="star" size="20" v-else @click="goodsCollectAdd()"></uni-icons>
                <view class="b-text">收藏</view>
            </view>
            <view class="action">
                <view class="add-cart" @click="handleFooterButtonClick('joinCart')">加入购物车</view>
                <view class="buy-now" @click="handleFooterButtonClick('buyNow')">立即购买</view>
            </view>
        </view>
        <u-popup :show="popupShow" :round="25">
            <view class="goods-spec-container">
                <view class="header">
                    <view class="price-wrapper">
                        <text class="unit">￥</text>
                        <text class="value" v-if="spec?.skuCode">{{spec.price}}</text>
                        <text class="value" v-else>{{unselectedPrice}}</text>
                    </view>
                    <u-icon name="close-circle-fill" color="#666666" @click="()=>{
                        popupShow=false
                        action=''
                    }"></u-icon>
                </view>
                <view class="main">
                    <view class="item" v-for="item,index in detail.attr" :key="index">
                        <view class="item-title">{{item.attrName}}&nbsp;({{item.attrValues.length}})</view>
                        <view class="item-value-container">
                            <view class="item-value" 
                            v-for="vv,ii in item.attrValues" 
                            :key="`${index}-${ii}`" 
                            @click="checkValue(index,vv)" 
                            :class="{
                                    active:selectedList[index]==`${item.attrName}:${vv.attrValueName}`,
                                    disabled:specList.filter((s)=>s.keyName.indexOf(`${item.attrName}:${vv.attrValueName}`)!=-1).length==0
                                }">
                                <img :src="vv.attrValueImage" v-if="item.setImage">
                                {{vv.attrValueName}}
                            </view>
                        </view>
                    </view>
                </view>
                <view class="number-container">
                    <view class="number-wrapper">
                        <span class="unit">数量</span>
                        <span class="value">(限购{{spec?.storeCount??9999}}件)有货</span>
                    </view>
                    <u-number-box v-model="form.quantity" disabledInput>    
                        <template #input>
                            <text style="width: 80rpx;text-align: center;">{{form.quantity}}</text>
                        </template>
                    </u-number-box>
                </view>
                <view class="footer">
                    <view class="action">
                        <view class="add" v-if="action=='joinCart'" @click="popupAction('joinCart')">加入购物车</view>
                        <view class="buy" v-else-if="action=='buyNow'" @click="popupAction('buyNow')">立即购买</view>
                        <template v-else>
                            <view class="add-cart" @click="popupAction('joinCart')">加入购物车</view>
                            <view class="buy-now" @click="popupAction('buyNow')">立即购买</view>
                        </template>
                    </view>
                </view>
            </view>
        </u-popup>
    </view>
</template>

<script setup lang="ts">
import { ref, computed} from "vue";
import { get, post } from "@/libs/request";
import { onLoad,onShow,onPullDownRefresh } from "@dcloudio/uni-app";
import { nav, roundToDecimal,swi } from "@/libs/utils"
interface detailType{
    goodsName:string
    goodsDesc:string
    goodsCover:string
    goodsContent:string
    goodsGallery:any[]
    unitName:string
    isHot:boolean
    isNew:boolean
    price:number
    spec:any[]
    attr:any[]
    collectId:number
}
const detail = ref<detailType>({
    goodsName:'',
    goodsDesc:'',
    goodsCover:'',
    goodsContent:'',
    goodsGallery:[],
    unitName:'',
    isHot:false,
    isNew:false,
    price:0.00,
    spec:[],
    attr:[],
    collectId:0
});
const swiperIndex = ref<number>(0);
const popupShow = ref<boolean>(false);
const form = ref<any>({
    goodsId:undefined,
    skuCode:undefined,
    quantity:1,
});
const selectedList = ref<any>(new Array(detail.value.attr.length));
const specList = ref<any[]>([]);
const action = ref<String>();
const cartTotal = ref<any>({
    totalQuantity:0,
    selectedQuantity:0,
    totalAmount:0.00,
});
/**
 * 规格名称
 */
const attrString = computed(()=>{
    return detail.value.attr.map((i)=>i.attrName).join(" ");
})
/**
 * 获取详情
 */
const getDetail = ()=>{
    get(`goods/detail/${form.value.goodsId}`).then((res)=>{
        if(res.errCode==0){
            detail.value = res.data;
        }
    })
}
/**
 * 获取购物车合计
 */
 const getCartTotal = ()=>{
    get(`car/getCartTotal`).then((res)=>{
        if(res.errCode==0){
            cartTotal.value = res.data;
        }
    })
}
/**
 * 选中值
 */
const checkValue = (key:number,value:any)=>{
    if(selectedList.value[key]==`${detail.value.attr[key].attrName}:${value.attrValueName}`){
        selectedList.value[key] = undefined;
    }else{
        let disabled = specList.value.filter((item)=>{
            return item.keyName.indexOf(`${detail.value.attr[key].attrName}:${value.attrValueName}`)!=-1;
        }).length;
        if(!disabled){
            return;
        }
        selectedList.value[key] = `${detail.value.attr[key].attrName}:${value.attrValueName}`;
    }
}
/**
 * 点击底部按钮
 * @param mode 
 */
const handleFooterButtonClick = (mode:"joinCart"|"buyNow")=>{
    // 打开选择规格框
    if(detail.value.spec.length>1){
        action.value = mode;
        popupShow.value = true;
    }else{
        if(!detail.value.spec[0].skuCode){
            uni.showToast({
                title: "商品下架或不存在",
                icon: "error",
                duration: 2000
            });
            return;
        }
        if(detail.value.spec[0].storeCount<form.value.storeCount){
            uni.showToast({
                title: "库存不足",
                icon: "error",
                duration: 2000
            });
            return;
        }
        form.value.skuCode = detail.value.spec[0].skuCode;
        if(mode=="joinCart"){
            postJoinCart();
        }else{
            postBuyNow();
        }
    }
}
/**
 * 点击弹窗按钮
 * @param mode 
 */
const popupAction = (mode:"joinCart"|"buyNow")=>{
    if(!spec.value.skuCode){
        uni.showToast({
            title: `请选择${attrString.value}`,
            icon: "none",
            duration: 2000
        });
        return;
    }
    if(spec.value.storeCount<form.value.storeCount){
        uni.showToast({
            title: "库存不足",
            icon: "error",
            duration: 2000
        });
        return;
    }
    form.value.skuCode = spec.value.skuCode;
    if(mode=="joinCart"){
        postJoinCart();
    }else{
        postBuyNow();
    }
}
/**
 * 请求添加购物车
 */
const postJoinCart = ()=>{
    post("car/add",{},form.value).then((res)=>{
        if(res.errCode==0){
            uni.showToast({
                title: "添加成功",
                icon: "success",
                duration: 2000
            });
            cartTotal.value = res.data;
            popupShow.value = false;
            action.value = '';
        }
    })
}
/**
 * 请求创建订单立即购买
 */
const postBuyNow = ()=>{
    nav(`/subpackage/order/pages/submit/index?goodsId=${form.value.goodsId}&skuCode=${form.value.skuCode}&quantity=${form.value.quantity}`)
}
/**
 * 未选中规格时的价格
 */
const unselectedPrice = computed(()=>{
    let priceList = detail.value.spec.map((item)=>{return item.price}).sort((a, b) => a - b);
    return priceList[0]==priceList[priceList.length-1]?roundToDecimal(priceList[0],2):`${roundToDecimal(priceList[0],2)}-${roundToDecimal(priceList[priceList.length-1],2)}`
})
/**
 * 选中的规格
 */
const spec = computed(()=>{
    specList.value = detail.value.spec.filter((i:any)=>i.storeCount>0);
    for (const item of selectedList.value) {
        specList.value = specList.value.filter((i)=>i.keyName.indexOf(item)!=-1 || item==undefined);
    }
    if(detail.value.attr.length != selectedList.value.filter((item:any) => item!=undefined).length){
        return {
            keyName:undefined,
            skuCode:undefined,
            storeCount:undefined,
        };
    }
    return specList.value[0];
})
/**
 * 添加收藏
 */
const goodsCollectAdd = ()=>{
    post(`goodsCollect/add`,{},{
        goodsId:form.value.goodsId
    }).then((res)=>{
        if(res.errCode==0){
            getDetail();
        }
    })
}
/**
 * 取消收藏
 */
const goodsCollectCancel = ()=>{
    post(`goodsCollect/cancel`,{},{
        goodsId:form.value.goodsId
    }).then((res:any)=>{
        if(res.errCode==0){
            getDetail();
        }
    })
}
onLoad((params: any)=>{
    form.value.goodsId = Number(params.id);
})
onShow(()=>{
    getDetail();
    getCartTotal();
})
/**
 * 下拉刷新
 */
onPullDownRefresh(async ()=>{
    await getDetail();
    await getCartTotal();
    uni.stopPullDownRefresh();
})
</script>

<style scoped lang="less">
.goods-detail-page{
    background: #f7f7f7;
    padding-bottom: 200px;
    .banner-box{
        position: relative;
        .banner{
            height: 750rpx;
            background: #7f7f7f;
            .item {
                &__inner {
                    display: flex;
                    height: 750rpx;
                    image {
                        width: 100vw;
                        height: 750rpx;
                        background-size: cover;
                        width: 100%;
                        height: 100%;
                    }
                }
            }
        }
        .indicator{
            position: absolute;
            bottom: 20rpx;
            right: 20rpx;
            border-radius: 100rpx;
            background:rgba(0, 0, 0, 0.4);
            text-align:center;
            line-height: 38rpx;
            color:#fff;
            font-size: 24rpx;;
            height: 38rpx;
            min-width: 74rpx;
        }
    }   
    .base-info{
        padding: 30rpx 35rpx;
        background: #fff;
        .price-wrapper{
            .unit{
                display: inline-block;
                color: #ff0000;
                font-weight: bold;
                font-size: 26rpx;
            }
            .value{
                display: inline-block;
                color: #ff0000;
                font-weight: bold;
                font-size: 36rpx;
            }
        }
        .name{
            display: block;
            margin-top: 10rpx;
            font-size: 36rpx;
            font-weight: bold;
            color: #333;
        }
        .bage-warp{
            height: 40rpx;
            display: flex;
            align-items: center;
            justify-self: flex-start;
            flex-wrap: wrap;
            .bage {
                border-radius: 6rpx;
                font-size: 20rpx;
                color: #fff;
                display: flex;
                align-items: center;
                justify-content: center;
                border-width: 1rpx;
                border-style: solid;
                font-weight: normal;
                display: inline;
                padding: 5rpx 8rpx;
                margin-right: 10rpx;
                font-weight: normal;
            }
            .new{
                background: #ECFFE7;
                border-color: #23AB04;
                color: #23AB04
            }
            .hot{
                background: #FFFFFF;
                border-color: #fc3247;
                color: #fc3247
            }
        }
    }
    .cell{
        margin-top: 20rpx;
        height: 100rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 35rpx;
        background: #fff;
        &-main{
            display: flex;
        }
        &-title{
            color: #666666;
            margin-right: 10rpx;
        }
        &-content{
            width: 500rpx;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }
    }
    .block {
        margin-top: 20rpx;
        padding: 30rpx 35rpx;
        background: #fff;
        &__label{
            display: block;
            font-size: 32rpx;
            color: #666666;
        }
    }
    .goods-detail{
        background-color: #fff;
        padding-bottom: 60rpx;
    }
    .tabbar{
        display: flex;
        align-items: center;
        justify-content: space-between;
        position: fixed;
        bottom: 0;
        z-index: 99;
        padding: 0 20rpx;
        padding-bottom: constant(safe-area-inset-bottom);
        padding-bottom: env(safe-area-inset-bottom);
        width: 100%;
        height: calc(120rpx + constant(safe-area-inset-bottom));
        height: calc(120rpx + env(safe-area-inset-bottom));
        background: #fff;
        box-sizing: border-box;
        box-shadow: 0 5rpx 10rpx 2rpx #1d1414;
        .btn{
            position:relative;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 80rpx;
            font-size: 30rpx;
            line-height: 40rpx;
            background: transparent;
            border: none;
            padding: 0 10rpx;
            .b-text{
                font-size: 20rpx;
                font-weight: 500;
                color: #666666;
            }
        }
        .action{
            height: 80rpx;
            line-height: 80rpx;
            border-radius: 100px;
            overflow: hidden;
            display: flex;
            font-size: 14px;
            .add-cart{
                background: linear-gradient(90deg, rgb(255, 205, 30), rgb(255, 138, 24));
                color: rgb(255, 255, 255);
                padding: 0 10rpx;
            }
            .buy-now{
                background: linear-gradient(90deg, rgb(254, 96, 53), rgb(239, 18, 36));
                color: rgb(255, 255, 255);
                padding: 0 30rpx;
            }
        }
    }
    .goods-spec-container{
        padding-top: 90rpx;
        padding-bottom: 120rpx;
        .header{
            width: 90%;
            top: 20rpx;
            left: 50%;
            transform: translateX(-50%);
            position: absolute;
            display: flex;
            justify-content: space-between;
            .price-wrapper{
                .unit{
                    display: inline-block;
                    color: #ff0000;
                    font-weight: bold;
                    font-size: 26rpx;
                }
                .value{
                    display: inline-block;
                    color: #ff0000;
                    font-weight: bold;
                    font-size: 36rpx;
                    box-sizing: border-box
                }
            }
        }
        .main{
            height: calc(500rpx + constant(safe-area-inset-bottom));
            height: calc(500rpx + env(safe-area-inset-bottom));
            border-top: 1px solid #f4f4f4;
            padding: 35rpx;
            overflow-y: auto;
            .item{
                margin-bottom: 40rpx;
                .item-title{
                    font-weight: bold;
                }
                .item-value-container{
                    display: flex;
                    .item-value{
                        display: flex;
                        align-items: center;
                        background: #f4f4f4;
                        padding: 10rpx;
                        margin: 10rpx;
                        border-radius: 10rpx;
                        font-size: 26rpx;
                        border: 2px solid #f4f4f4;
                        image{
                            width: 100rpx;
                            height: 100rpx;
                            margin-right: 10rpx;
                        }
                    }
                    .disabled{
                        opacity: 0.4;
                    }
                    .active{
                        border: 2px solid #ff0000;
                        background: #FFFFFF;
                    }
                }
            }
        }
        .number-container{
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 35rpx;
            .unit{
                font-weight: bold;
                margin-right: 10rpx;
            }
            .value{
                font-size: 24rpx;
                color: #666666;
            }
        }
    }
    .footer{
        width: 100%;
        background: #FFFFFF;
        position:absolute;
        bottom: 10rpx;
        left: 50%;
        transform: translateX(-50%);
        .action{
            height: 80rpx;
            line-height: 80rpx;
            border-radius: 100px;
            overflow: hidden;
            display: flex;
            justify-content: center;
            font-size: 14px;
            .add{
                background: linear-gradient(90deg, rgb(255, 205, 30), rgb(255, 138, 24));
                color: rgb(255, 255, 255);
                border-radius:100rpx;
                padding: 0 280rpx;
            }
            .add-cart{
                background: linear-gradient(90deg, rgb(255, 205, 30), rgb(255, 138, 24));
                color: rgb(255, 255, 255);
                padding: 0 80rpx;
                border-top-left-radius:100rpx;
                border-bottom-left-radius:100rpx;
            }
            .buy{
                background: linear-gradient(90deg, rgb(254, 96, 53), rgb(239, 18, 36));
                color: rgb(255, 255, 255);
                border-radius:100rpx;
                padding: 0 280rpx;
            }
            .buy-now{
                background: linear-gradient(90deg, rgb(254, 96, 53), rgb(239, 18, 36));
                color: rgb(255, 255, 255);
                padding: 0 100rpx;
                border-top-right-radius:100rpx;
                border-bottom-right-radius:100rpx;
            }
        }
    }
}
</style>